package com.example.mydy;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.mydy.model.UserData;
import com.example.mydy.api.UserApi;
import com.example.mydy.utils.NetworkUtils;
import com.example.mydy.utils.CacheUtils;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MyActivity extends AppCompatActivity {
    private static final String TAG = "MyActivity";
    private static final String PREFS_NAME = "MyAppPrefs";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_TOKEN = "token";
    private static final String KEY_USER_NICKNAME = "userNickname";
    private static final String KEY_USER_TYPE = "userType";
    private static final String KEY_LEVEL = "level";
    private static final String KEY_BALANCE = "balance";
    private static final String KEY_IS_LOGGED_IN = "isLoggedIn";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        boolean isLoggedIn = sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
        String token = sharedPreferences.getString(KEY_TOKEN, "");
        
        if (!isLoggedIn || token.isEmpty()) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            navigateToLogin();
            return;
        }

        // 尝试从SharedPreferences加载缓存的用户信息
        loadCachedUserInfo();
        
        // 同时从服务器获取最新的用户信息
        loadUserInfo();

        setupNavigationBarClickListeners();
        setupFunctionAreaClickListeners();
    }
    
    private void loadCachedUserInfo() {
        SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String nickname = sharedPreferences.getString(KEY_USER_NICKNAME, "");
        String level = sharedPreferences.getString(KEY_LEVEL, "");
        float balance = sharedPreferences.getFloat(KEY_BALANCE, 0);
        
        if (!nickname.isEmpty()) {
            TextView userNicknameTextView = findViewById(R.id.username);
            TextView userLevelTextView = findViewById(R.id.user_level);
            TextView amountTextView = findViewById(R.id.amount);
            
            userNicknameTextView.setText(nickname);
            userLevelTextView.setText("等级 " + level);
            amountTextView.setText(String.format("%.2f", balance));
        }
    }
    
    private void loadUserInfo() {
        // 如果是离线模式，从MockDataManager获取用户数据
        if (NetworkUtils.USE_OFFLINE_MODE) {
            Log.d(TAG, "离线模式：从MockDataManager获取用户数据");
            
            SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
            String username = sharedPreferences.getString(KEY_USERNAME, "");
            
            if (username.isEmpty()) {
                return;
            }
            
            // 从MockDataManager获取用户信息
            com.example.mydy.model.UserInfo userInfo = com.example.mydy.utils.MockDataManager.getInstance().getCurrentUser();
            if (userInfo != null) {
                // 更新UI
                TextView userNicknameTextView = findViewById(R.id.username);
                TextView userLevelTextView = findViewById(R.id.user_level);
                TextView amountTextView = findViewById(R.id.amount);
                
                userNicknameTextView.setText(userInfo.getNickname());
                userLevelTextView.setText("等级 " + userInfo.getLevel());
                
                double balance = 0.0;
                try {
                    String balanceStr = userInfo.getBalance();
                    if (balanceStr != null && !balanceStr.isEmpty()) {
                        balance = Double.parseDouble(balanceStr);
                    }
                } catch (NumberFormatException e) {
                    Log.e(TAG, "解析余额失败: " + e.getMessage());
                }
                
                amountTextView.setText(String.format("%.2f", balance));
            } else {
                Log.e(TAG, "离线模式：未找到用户数据");
            }
            
            return;
        }

        if (!NetworkUtils.isNetworkAvailable(this)) {
            Toast.makeText(this, "网络连接不可用", Toast.LENGTH_SHORT).show();
            return;
        }

        SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String username = sharedPreferences.getString(KEY_USERNAME, "");
        String token = sharedPreferences.getString(KEY_TOKEN, "");
        
        if (username.isEmpty() || token.isEmpty()) {
            return;
        }

        UserApi userApi = NetworkUtils.getUserApi();
        userApi.getUserData(username).enqueue(new Callback<UserData>() {
            @Override
            public void onResponse(Call<UserData> call, Response<UserData> response) {
                if (response.isSuccessful()) {
                    UserData userData = response.body();
                    if (userData != null && userData.isValid()) {
                        updateUI(userData);
                        cacheUserInfo(userData);
                    } else {
                        Log.e(TAG, "获取的用户数据无效");
                        Toast.makeText(MyActivity.this, "获取的用户数据无效", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Log.e(TAG, "获取用户数据失败: 响应体为空或错误");
                    Toast.makeText(MyActivity.this, "获取用户数据失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<UserData> call, Throwable t) {
                Log.e(TAG, "获取用户数据失败，网络连接问题", t);
                Toast.makeText(MyActivity.this, "网络连接问题", Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void cacheUserInfo(UserData userData) {
        SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
        editor.putString(KEY_USER_NICKNAME, userData.getUserNickname());
        editor.putString(KEY_LEVEL, userData.getLevel());
        editor.putFloat(KEY_BALANCE, (float) userData.getUserBalance());
        editor.apply();
    }

    private void updateUI(UserData userData) {
        TextView userNicknameTextView = findViewById(R.id.username);
        TextView userLevelTextView = findViewById(R.id.user_level);
        TextView amountTextView = findViewById(R.id.amount);

        userNicknameTextView.setText(userData.getUserNickname());
        userLevelTextView.setText("等级 " + userData.getLevel());
        amountTextView.setText(String.format("%.2f", userData.getUserBalance()));
    }

    private void setupNavigationBarClickListeners() {
        // 获取底部导航视图
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
        
        // 设置当前选中项为"我的"
        bottomNavigationView.setSelectedItemId(R.id.nav_my);
        
        // 设置导航菜单项选择监听器
        bottomNavigationView.setOnItemSelectedListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.nav_home) {
                // 先设置选中项为首页，然后再跳转
                bottomNavigationView.setSelectedItemId(R.id.nav_home);
                startActivity(new Intent(this, MainActivity.class));
                finish();
                return true;
            } else if (itemId == R.id.nav_advertisement) {
                // 先设置选中项为广告，然后再跳转
                bottomNavigationView.setSelectedItemId(R.id.nav_advertisement);
                startActivity(new Intent(this, AdvertisementListActivity.class));
                finish();
                return true;
            } else if (itemId == R.id.nav_project) {
                // 先设置选中项为项目，然后再跳转
                bottomNavigationView.setSelectedItemId(R.id.nav_project);
                startActivity(new Intent(this, ProjectActivity.class));
                finish();
                return true;
            } else if (itemId == R.id.nav_promotion) {
                // 先设置选中项为推广，然后再跳转
                bottomNavigationView.setSelectedItemId(R.id.nav_promotion);
                startActivity(new Intent(this, PromotionActivity.class));
                finish();
                return true;
            } else if (itemId == R.id.nav_my) {
                // 当前页面，无需操作
                return true;
            }
            return false;
        });
    }

    private void setupFunctionAreaClickListeners() {
        // 系统设置
        findViewById(R.id.system_settings).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyActivity.this, SystemSettingsActivity.class);
                startActivity(intent);
            }
        });

        // APP 下载地址
        findViewById(R.id.app_download).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String downloadUrl = "https://example.com/app/download";
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(downloadUrl));
                startActivity(intent);
            }
        });

        // 关注公众号
        findViewById(R.id.follow_public_account).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String publicAccountUrl = "https://open.weixin.qq.com/qr/code?username=your_public_account_username";
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(publicAccountUrl));
                startActivity(intent);
            }
        });

        // 添加提现功能
        findViewById(R.id.withdraw).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent = new Intent(MyActivity.this, com.example.mydy.withdraw.WithdrawActivity.class);
                    startActivity(intent);
                } catch (Exception e) {
                    Log.e(TAG, "无法启动WithdrawActivity: " + e.getMessage(), e);
                    Toast.makeText(MyActivity.this, "正在加载提现页面...", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 退出账户
        findViewById(R.id.logout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });

        // 登录按钮（如果未登录时显示）
        findViewById(R.id.my_activity_login_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                navigateToLogin();
            }
        });
    }
    
    private void logout() {
        SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
        editor.clear();
        editor.apply();
        
        CacheUtils.clearCache(this);
        NetworkUtils.clearRetrofit();
        
        Toast.makeText(this, "已退出登录", Toast.LENGTH_SHORT).show();
        navigateToLogin();
    }
    
    private void navigateToLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        // 用户已登录，按返回键时返回主页而不是登录页面
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}